<?php
declare(strict_types = 1);

namespace app\service;

use app\common\BaseService;
use app\model\Admin;
use app\utils\JwtUtil;

class AdminService extends BaseService
{
    //构建方法
    public function __construct()
    {
        $this->model = new Admin();

        //设置当前对应模型默认的查询字段
        $this -> name = 'username';

        //默认允许的查询字段
        $this -> allowField = ['id', 'username', 'role_id', 'status', 'create_time', 'avatar', 'nickname', 'mobile', 'email'];
    }
    //重构更新方法
    public function update($id, $data)
    {
        //获取管理员信息
        $result = $this->model->find($id);
        if($result){
            //判断是否修改密码
            if (isset($data['password']) && !empty($data['password'])) {
                //确保数据加密，但是密码盐不改
                $data['salt'] = $result['salt'];
                $data['password'] = md5(md5($data['password']).$data['salt']);
            }
            return $result->save($data);
        }else{
            return false;
        }

    }

    //登录方法
    public function login($username, $password)
    {
        $this->allowField = ['*']; //临时允许所有字段
        //通过用户名查找用户信息
        $info = $this->getInfoByName($username);
        if(!$info){
            return false;
        }
        $password = md5(md5($password).$info->salt); //加密后的输入密码
        if($password != $info->password){
            return false;
        }
        //新增
        $roleservice = new RoleService();
        //获取角色组的key
        $role_key = $roleservice->getInfoById($info->role_id)['key'];
        //签发证书
        $jwt = JwtUtil::issue($info->id, $role_key);
        return ['token' => $jwt];
    }

    //创建方法 getWithRole
    public function getWithRole()
    {
        //角色服务
        $roleservice = new RoleService();
        $result = $this->getListAll();
        if(!empty($result)){
            foreach ($result as &$item){
                $role = $roleservice->getInfoById($item['role_id']);
                //获取角色组名称
                $item['role_name'] = $role->name;
            }
        }
        return $result;
    }
}